<template>
   <div class="main">
        <div class="top-box">
            <div class="search">
                <el-input
                    placeholder="请输入内容"
                    v-model="input4"
                    @keyup.enter.native="search">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
            </div>
            <div class="buy-box" v-show="showJs" @mouseover="mouse_over" @mouseout="mouseout">
                <el-checkbox-group @change="checkbox_change" v-model="checkList" class="buy-good-box" v-for="(item,index) in buyGoods" :key="index">
                    <el-checkbox :label="item.id">
                      <img :src="item.url"/>
                      <div class="des">{{item.descript}}</div>
                      <div class="buy-price">&yen;{{item.price}}</div>
                      <div @click.stop.prevent.self style="display:inline">
                        <el-input-number v-model="item.num" @change="(current,old)=>{handleChange(current,old,item)}" :min="0" :max="10" ></el-input-number>
                      </div>
                  </el-checkbox>
                  </el-checkbox-group>
                <div class="buy-btn-box">
                    <div>合计:{{sum}}</div>
                    <div :class="$route.query.coupon_id?'':'coupon'" @click="use_cupon">{{$route.query.coupon_id?'优惠后：'+after_sum:'选择优惠券'}}</div>
                    <el-button type="danger" @click="count_handler">结算</el-button>
                </div>
            </div>
            <i class="el-icon-s-goods cart" @mouseenter="mouse_enter" @mouseout="mouseout"></i>
            <i class="el-icon-s-order order" @click="order_handler"></i>
            <div class="info">
              <div class="name" v-if="name=='游客'">游客</div>
              <!-- 去登录和游客上下居中 -->
              <div class="name" v-if="name=='游客'" @click="$router.push('/login')" style="cursor: pointer; color: #fff; font-size: 12px; display: flex; align-items: end; justify-content: center;">去登录></div>
              <el-dropdown v-else @command="handleCommand">
                <span class="el-dropdown-link">
                  {{ name }}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
        </div>
        <div class="content-box">
            <div class="left-box">
                <div class="menu-item">
                   <div :class="$route.params.type==item.id?'item active':'item'" v-for="(item,index) in menu" :key="index" @click="type_change(item.id)"> {{item.text}}</div>
                </div>
            </div>
            <div class="right-box">
              <div class="good-box" >
                  <div class="good-item" v-for="(i,j) in good_list" :key="j" @click="good_detail(i.type,i.id)">
                      <img :src="i.img"/>
                      <div class="good-content">
                          <div class="title">{{i.title}}</div>
                          <div class="title2">
                              <div class="price">&yen;{{i.price}}</div>
                              <el-button type="danger" size="small" plain @click.stop="add_cart(i)">  加入购物车</el-button>
                          </div>
                      </div>
                  </div>
              </div>
              <div class="page">
                <el-pagination
                layout="prev, pager, next"
                :total="total"
                @prev-click="current_change"
                @next-click="current_change"
                @current-change="current_change">
                </el-pagination>
              </div>
              
            </div>
        </div>
    </div>
</template>
<script>
import {cart_list,cart_add,cart_del} from "@/api/cart_api"
import { category_list } from "@/api/category_api"
import { coupon_info } from "@/api/coupon_api"
import {list,good_by_id,search} from "@/api/goods_api"
import { logout } from "@/api/user_api"
export default{
  data(){
    return{
      pageMap:{
        limit:14,
        now_page:1,
        key:"",
        id:this.$route.params.type
      },
      total:0,
      checkList:[],
      name:"",
      input4:"",
      num:1,
      after_sum:0,
      timeout:"",
      sum:0,
      buyGoods:[],
      showJs:false,
      menu:[],
      good_list:[]
    }
  },
  methods:{
    type_change(type){
      this.$router.push(`/index/${type}`)
    },
    order_handler(){
      const user = localStorage.getItem('user')
      if(!user){
        this.$message({
          type:'info',
          message:'请先登录'
        })
        return
      }
      this.$router.push('/user_order')

    },
    count_handler(){
      if(!this.sum){
        this.$message({
          type:'warning',
          message:'请先选择商品'
        })
        return
      }
      let user_id = JSON.parse(localStorage.getItem('user')).user_id
      let date = new Date()
      let data = this.buyGoods.filter(v=>this.checkList.some(m=>m==v.id)).map(k=>{
        return {
          user_id:user_id,
          good_id:k.id,
          price:k.price,
          num:k.num,
          time:date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()
        }
      })

      this.$router.push(`/order?data=${JSON.stringify({coupon_id:1,data})}&price=${this.after_sum!=0?this.after_sum:this.sum}`)
      
    },
    async logout(){
      const {data:res} = await logout()
      this.$message({
        type:res.code==200?'success':'error',
        message:res.message
      })
      if(res.code==200){
        localStorage.clear()
        this.name = "游客"
      }
    },
    async search(){
      const res = await search(this.input4)
      this.editableTabs[0].content = res.data.data.map((k)=>{
        return {
          id:k.id,
          url:this.revert(k.img),
          num:1,
          title:k.title,
          price:k.price,
          descript:k.des
        }
      })
      
    },
    mouse_over(){
      clearTimeout(this.timeout)
    },
    async checkbox_change(val){
      if(val.length==0){
        this.sum = 0
      }else{
        let sum =0
        this.buyGoods.filter(v=>this.checkList.some(m=>m==v.id)).forEach((item,index)=>{
                 sum+=item.num*item.price
               })
        if(this.$route.query.coupon_id){
          const {data:res} = await coupon_info(this.$route.query.coupon_id)
          this.after_sum = Math.ceil(sum*res.data.discount_value)
        }
        
        this.sum = sum
    }
    },
    async mouse_enter(){
      if(this.name=='游客'){
        this.$message({
          type:'info',
          message:'请先登录'
        })
        return
      }
      clearTimeout(this.timeout)
      this.showJs = true
      await this.get_cart_list()
    },
    async get_cart_list(){
      const res = await cart_list(JSON.parse(localStorage.getItem('user')).user_id)
      this.buyGoods = await Promise.all(res.data.data.map(async item=>{
        const r = await good_by_id(item.goods_id)
        return {
          id:item.goods_id,
          url:this.revert(r.data.data.img),
          num:item.num,
          title:r.data.data.title,
          price:r.data.data.price,
          descript:r.data.data.des
        }
      }))
    },
    mouseout(){
      this.timeout = setTimeout(()=>{
        this.showJs = false
      },1000)
    },
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      if(activeName=='0')this.flag = true
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
    },
    tab_click(e){
        this.flag =e.name==0?true:false
    },
    use_cupon(){
      if(this.$route.query?.coupon_id) return
      this.$router.push(`/coupon?type_id=${this.$route.params.type}`)
    },
    async handleChange(crt,old,good){
      if(this.name=='游客'){
        this.$message({
          type:'info',
          message:'请先登录'
        })
        return
      }
      //增加
      if(crt>old){
        await cart_add(good.id,JSON.parse(localStorage.getItem('user')).user_id,crt-old)
      }else{
        await cart_del(good.id,JSON.parse(localStorage.getItem('user')).user_id,old,old-crt)
      }
      this.checkbox_change(this.checkList)
       this.get_cart_list()
    },
    async add_cart(good,T){
      if(this.name=='游客'){
        this.$message({
          type:'info',
          message:'请先登录'
        })
        return
      }
      const res = await cart_add(good.id,JSON.parse(localStorage.getItem('user')).user_id,T?this.num:1)
      this.$message({
          type:res.data.code==200?'success':'error',
          message:res.data.msg
        })
      this.num=1
    },
    good_detail(type,id){
      this.$router.push(`/index/${type}/${id}`)
    },
    async get_category_list(){
      const {data:res} = await category_list()
      this.menu= res.data
    },
    revert(data){
      var parts = data.split(';base64,'),
      contentType = parts[0].split(':')[1],
      raw = window.atob(parts[1]),
      length = raw.length,
      arr = new Uint8Array(length);
      for (var i = 0; i < length; i++) {
          arr[i] = raw.charCodeAt(i);
      }
      var blob = new Blob([arr], { type: contentType });
      return URL.createObjectURL(blob);
    },
    current_change(page){
      this.pageMap.now_page = page
      this.get_good_list()
    },
    async get_good_list(){
      const {data:res}  = await list(this.pageMap)
      if(res.data.total==0){
        this.$message({
          type:'info',
          message:"当前分类暂无商品"
        })
        return
      }
      this.total = res.data.total
      this.good_list=res.data.list.map(k=>{
         k.img=this.revert(k.img)
         return k
      })
    },
    handleCommand(command) {
      if (command === 'logout') {
        this.logout()
      } else if (command === 'profile') {
        this.$router.push('/profile')
      }
    }
  },
 async created(){  
      this.$notify({
        title:"提示",
        type:'info',
        duration:0,
        dangerouslyUseHTMLString: true,
        message:'<div style="color:teal">测试账号：123   测试密码:123</br>管理账号：root  管理密码：root</div>'
      })
      if(this.$route.query.flag){
        this.mouse_enter()
      }
      
      this.name = localStorage.getItem('user')?JSON.parse(localStorage.getItem('user')).username:"游客"
      this.get_good_list()
      this.get_category_list()
      // 检查是否已绑定邮箱
      if (this.name !== '游客') {
        const user = JSON.parse(localStorage.getItem('user'))
        if (!user.email) {
          this.$notify({
            title: '提示',
            dangerouslyUseHTMLString: true,
            message: '<div>您尚未绑定邮箱，建议尽快绑定邮箱以保障账户安全<br/><a style="color: #409EFF; cursor: pointer;" onclick="window.location.href=\'/profile\'">去绑定 ></a></div>',
            type: 'warning',
            duration: 0,
            position: 'bottom-right'
          })
        }
      }
  }

}
</script>
<style scoped lang="scss">
.main{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  .top-box{
    width: 100%;
    height: 15%;
    background-color: #0071DC;
    display: flex;
    justify-content: center;
    align-items: center;
    .search{
      width: 60%;
      .el-input__inner{
        border-radius: 50px;
      }
    }
    .info{
      position: absolute;
      color: #fff;
      right: 2%;
      cursor: pointer;
      display: flex;
      width: 5%;
      justify-content: space-between;
      .login{
        &:hover{
        color: #002D58;
      }
      }
      
    }
    .buy-box{
      position: absolute;
      width: 60%;
      height: 60%;
      top: 8%;
      left: 18%;
      z-index: 10;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      padding: 10px;
      border: 1px #f2f2f2 solid;
      border-radius: 10px;
      overflow-y: scroll;
      .buy-good-box{
        .el-checkbox{
          width: 100%;
          display: flex;
          align-items: center;
        }
        background-color: #F7F7F7;
        padding: 10px;
        border-radius: 5px;
        display: flex;
        align-items: center;
        margin: 15px 0;
        justify-content: space-around;
        img{
          width: 15%;
          border-radius: 5px;
          cursor: pointer;
        }
        .des{
          margin: 0 10px;
          cursor: pointer;
          &:hover{
            color:#FF5000;
          }
        }
        .buy-price{
          color: red;
          margin: 0 5px;
        }
      }
      .buy-btn-box{
        background-color: #fff;
        position: fixed;
        bottom: 2%;
        right:5%;
        border: 2px #f2f2f2 solid;
        width: 30%;
        display: flex;
        align-items: center;
        justify-content: space-around;
        height: 8%;
        border-radius: 5px;
        .coupon{
          text-decoration: underline;
          cursor: pointer;
          &:hover{
            color: #0071DC;
          }
        }
      }
    }
    .cart{
      font-size: 40px;
      color:#fff;
      cursor: pointer;
      &:hover{
        color: #002D58;
      }
    }
    .order{
      margin-left: 10px;
      font-size: 40px;
      color:#fff;
      cursor: pointer;
      &:hover{
        color: #002D58;
      }
    }
  }
  .content-box{
    display: flex;
    width: 100%;
    height: 85%;
    .left-box{
      width: 20%;
      margin: 2%;
      height: 95%;
      background-color: #F7F7F7;
      line-height: 50px;

      .menu-item{
        margin: 5px;
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        .item{
          width: 25%;
          display: flex;
          justify-content: center;
          cursor: pointer;
          &.active{
            color: #0071DC;
          }
          &:hover{
            color: #0071DC;
          }
        }
      }
    }
    .right-box{
      height: 100%;
      width: 80%;
      display: flex;
      overflow-y: scroll;
      flex-direction: column;
          .good-box{
            display: flex;
            flex-wrap: wrap;
            .good-item{
              height: 300px;
              width: 200px;
              border-radius: 10px;
              margin: 10px;
              cursor: pointer;
              border: 1px #fff solid;
              img{
                width: 97%;
                border-radius: 10px;
                margin: 3px;
              }
              .title{
                margin-top: 10px;
                padding: 5px;
                width: 200px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
              .title2{
                margin-top: 10px;
                display: flex;
                padding: 0 5px;
                justify-content: space-between;
                align-items: center;
                .price{
                  color:red;
                }
              }
              &:hover{
                border: 1px red solid;
              }
            }
          }
          .cart-box{
            display: flex;
            margin: 50px 10px;
            img{
              width: 50%;
              border-radius: 10px;
            }
            .cart-right{
              display: flex;
              flex-direction: column;
              padding: 10px;
              justify-content: space-around;
              margin-left: 20px;
              .cart-descript{
                font-weight: bold;
                font-size: 25px;
              }
              .cart-price{
                font-size: larger;
                font-weight: bold;
                color: red;
              }
              .cart-btn{
                display: flex;
                align-items: center;
                justify-content: end;
                
                button{
                  margin: 10px;
                }
                
              }
            }
          }
        .right{

        }
      
    }
  }
}
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
</style>
